import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'

// 创建axios实例
const service = axios.create({
  timeout: 60000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * code为非1是抛错
    */

    // 导出文件
    const headers = response.headers
    if (headers['content-type'] === 'application/octet-stream;charset=UTF-8') { // 附件下载 返回头类型判断
      const content = response.data
      const blob = new Blob([content])
      let newname = headers["content-disposition"].split("filename=")[1]
      let fileName = decodeURIComponent(newname.split(".")[0]) + '.' + newname.split(".")[1]
      if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
      return
    }

    const res = response.data
    if (res.code !== 1) {
      // -999:授权失败重新登录;
      if (res.code === -999) {
        MessageBox.alert('授权过期，请重新登录！', '重新登录', {
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
        return
      }

      let msg = res.msg
      if (msg == '') {
        msg = '网络故障'
      }
      Message({
        message: msg,
        type: 'error',
        duration: 3 * 1000
      })

      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug

    Message({
      message: '服务器故障！',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)


export default service
